package fetcher

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"my-crawler/concurrence/engine"
	"net/http"
	"strings"
)

type PostReq struct {
}

// Post json 请求方式 ajax
func (r *PostReq) Request(ReqData engine.ReqData) ([]byte, error) {
	<-ReqData.Rate
	var url string
	if ReqData.Url == "" {
		panic("No Request Url！")
	}
	fmt.Println(ReqData)
	//拼接url
	url = ReqData.Url
	data := ReqData.Payload
	header := ReqData.Header
	client := http.Client{}

	jsonData, _ := json.Marshal(data)
	req, err := http.NewRequest(
		http.MethodPost,
		url,
		strings.NewReader(string(jsonData)))
	//添加header
	if ct, ok := header["Content-Type"]; ok {
		req.Header.Add("Content-Type", ct)
	}
	if ck, ok := header["Cookie"]; ok {
		req.Header.Add("cookie", ck)
	}
	if ug, ok := header["User-Agent"]; ok {
		req.Header.Add("User-Agent", ug)
	}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("post failed, err:%v\n", err)
		return nil, err
	}
	defer resp.Body.Close()
	all, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get resp failed,err:%v\n", err)
		return nil, err
	}
	fmt.Println(string(all))
	return all, nil
}
